/**
 * ConnectionUtils.java
 *
 * @author Beatrice Bacelli
 * @author Luca Bedogni
 * @author Silvia Righini
 */
package unibo.lsb.communication;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.ExportException;

import unibo.lsb.exception.TokioException;
import unibo.lsb.server.ConfigurationConstants;

public class ConnectionUtils {

	static Registry reg = null;

	public static Registry launchRMIRegistry() throws TokioException {
		if (reg != null) {
			System.err.println("CU01: Registry already running.");
			return reg;
		}
		try {
			// getting local registry
			LocateRegistry
					.createRegistry(ConfigurationConstants.RMIREGISTRYPORT);
			reg = LocateRegistry.getRegistry(ConfigurationConstants.SERVER_IP,
					ConfigurationConstants.RMIREGISTRYPORT);
		} catch (Exception e) {
			System.err.println("CU02: RMI registry already running");
			// System.err.println(e.getMessage());
			// e.printStackTrace();
			throw new TokioException("RMIregistry already in use on port "
					+ ConfigurationConstants.RMIREGISTRYPORT + ".",
					"Registry error");
		}
		return reg;
	}

	public static int launchRMIRegistry(int port) throws TokioException {
		Registry reg = null;
		boolean launched = false;
		while (reg == null && launched == false) {
			try {
				// getting local registry
				LocateRegistry.createRegistry(port);
				reg = LocateRegistry.getRegistry(
						ConfigurationConstants.SERVER_IP, port);
				launched = true;
			} catch (ExportException ee) {
				port--;
				launched = false;
			} catch (Exception e) {
				System.err.println(e.getMessage());
				e.printStackTrace();
				throw new TokioException(
						"CU03: RMIregistry already in use on port " + port
								+ ".", "Registry error");
			}
		}

		return port;
	}

	public static void bindService(Remote obj, String ip, String registryPort,
			String serviceName) throws RemoteException, MalformedURLException {

		String objectURL = "rmi://" + ip + ":" + registryPort + "/"
				+ serviceName;
		Naming.rebind(objectURL, obj);
	}

	public static void bindService(Remote obj, String ip, int registryPort,
			String serviceName) throws RemoteException, MalformedURLException {
		bindService(obj, ip, (new Integer(registryPort)).toString(),
				serviceName);
	}
}
